import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import '../App.css'
import {
    List,
    Image,
    Stepper,
    Checkbox,
    Button,
    Card,
    Tag,
    Divider,
    Modal
} from 'antd-mobile'
import axios from 'axios'


function Gou() {
    const navigate = useNavigate()
    const [list, setlist] = useState([])
    const [list1, setlist1] = useState([])
    const [selectedItems, setSelectedItems] = useState([])
    const [quantities, setQuantities] = useState({})
    const [deleteModalVisible, setDeleteModalVisible] = useState(false)
    const [itemToDelete, setItemToDelete] = useState(null)
    
    const handleCheckout = () => {
        if (selectedItems.length === 0) {
            Modal.alert({
                content: '请先选择要结算的商品',
            })
            return
        }
        
        // 将选中的商品信息传递到确认订单页面
        const selectedProducts = selectedItems.map(itemTitle => {
            const item = list.find(item => item.title === itemTitle)
            return {
                ...item,
                quantity: quantities[itemTitle] || 1
            }
        })
        
        // 将数据存储到localStorage，供确认订单页面使用
        localStorage.setItem('selectedProducts', JSON.stringify(selectedProducts))
        localStorage.setItem('totalAmount', calculateTotal().toString())
        
        navigate('/jie')
    }
    useEffect(() => {
        getlist()
        getlist1()

        // 确保结算栏固定在底部
        const ensureCheckoutBarFixed = () => {
            const checkoutBar = document.querySelector('.fixed-checkout-bar')
            if (checkoutBar) {
                checkoutBar.style.position = 'fixed'
                checkoutBar.style.bottom = '0'
                checkoutBar.style.left = '0'
                checkoutBar.style.right = '0'
                checkoutBar.style.zIndex = '999999'
            }
        }

        // 页面加载时执行
        ensureCheckoutBarFixed()

        // 监听滚动事件，确保结算栏始终固定
        window.addEventListener('scroll', ensureCheckoutBarFixed)
        window.addEventListener('resize', ensureCheckoutBarFixed)

        // 清理事件监听器
        return () => {
            window.removeEventListener('scroll', ensureCheckoutBarFixed)
            window.removeEventListener('resize', ensureCheckoutBarFixed)
        }
    }, [])

    const getlist1 = async () => {
        const res = await axios.get('http://localhost:3000/list1')
            .then(res => {
                setlist1(res.data.list1)
            })
    }

    const getlist = async () => {
        const res = await axios.get('http://localhost:3000/list')
            .then(res => {
                setlist(res.data.list)
                const initialQuantities = {}
                res.data.list.forEach(item => {
                    initialQuantities[item.title] = 1
                })
                setQuantities(initialQuantities)
            })
    }

    const handleItemSelect = (itemName) => {
        setSelectedItems(prev => {
            const newSelected = prev.includes(itemName)
                ? prev.filter(name => name !== itemName)
                : [...prev, itemName]
            console.log('🔘 商品选择变化:', itemName, '选中状态:', !prev.includes(itemName))
            console.log('📋 当前选中商品列表:', newSelected)
            return newSelected
        })
    }

    const handleSelectAll = (checked) => {
        const newSelected = checked ? list.map(item => item.title) : []
        console.log('✅ 全选操作:', checked ? '全选' : '取消全选')
        console.log('📋 选中商品列表:', newSelected)
        setSelectedItems(newSelected)
    }

    const handleQuantityChange = (itemName, value) => {
        const oldQuantity = quantities[itemName] || 1
        console.log('🔢 数量变化:', itemName, `${oldQuantity} → ${value}`)
        setQuantities(prev => ({
            ...prev,
            [itemName]: value
        }))
    }

    const calculateTotal = () => {
        if (selectedItems.length === 0) {
            console.log('💰 总计: ¥0.00 (未选择任何商品)')
            return 0
        }

        const total = selectedItems.reduce((total, itemTitle) => {
            const item = list.find(item => item.title === itemTitle)
            const quantity = quantities[itemTitle] || 1
            const itemTotal = (item?.price || 0) * quantity
            console.log(`📦 商品: ${itemTitle}`)
            console.log(`   💰 单价: ¥${item?.price}`)
            console.log(`   🔢 数量: ${quantity}`)
            console.log(`   💵 小计: ¥${itemTotal.toFixed(2)}`)
            return total + itemTotal
        }, 0)

        console.log('💰 总计: ¥' + total.toFixed(2))
        return total
    }

    const showDeleteModal = (item) => {
        setItemToDelete(item)
        setDeleteModalVisible(true)
    }

    const handleDelete = async () => {
        if (!itemToDelete) return

        try {
            await axios.delete(`http://localhost:3000/list/${itemToDelete._id}`)

            // 从选中列表中移除该商品
            setSelectedItems(prev => prev.filter(name => name !== itemToDelete.title))

            // 重新获取列表
            getlist()

            // 关闭模态框
            setDeleteModalVisible(false)
            setItemToDelete(null)
        } catch (error) {
            console.error('删除失败:', error)
            Modal.alert({
                content: '删除失败，请重试',
            })
        }
    }

    const cancelDelete = () => {
        setDeleteModalVisible(false)
        setItemToDelete(null)
    }

    // 检查是否全选
    const isAllSelected = list.length > 0 && selectedItems.length === list.length

    return (
        <div
            className="page-content"
            style={{
                backgroundColor: '#f5f5f5',
                position: 'relative',
                paddingBottom: list.length > 0 ? '170px' : '0',
                maxWidth: '768px',
                margin: '0 auto',
                boxShadow: '0 0 10px rgba(0,0,0,0.05)'
            }}
        >
            {/* 购物车标题 */}
            <div style={{
                backgroundColor: '#fff',
                padding: '8px', // 从16px改为8px
                textAlign: 'center',
                borderBottom: '1px solid #f0f0f0'
            }}>
                <div style={{
                    fontSize: '18px',
                    fontWeight: 'bold',
                    color: '#333'
                }}>
                    购物车
                </div>
            </div>

            {/* 购物车商品列表 */}
            {list.length === 0 ? (
                // 空购物车显示
                <div style={{
                    backgroundColor: '#fff',
                    padding: '40px 20px',
                    textAlign: 'center',
                    marginBottom: '8px'
                }}>
                    {/* 购物车图标 */}
                    <div style={{
                        fontSize: '80px',
                        color: '#ffd700',
                        marginBottom: '20px'
                    }}>
                        🛒
                    </div>

                    {/* 空购物车文字 */}
                    <div style={{
                        fontSize: '16px',
                        color: '#666',
                        marginBottom: '30px'
                    }}>
                        购物车为空
                    </div>

                    {/* 去逛逛按钮 */}
                    <Button
                        color='primary'
                        size='middle'
                        style={{
                            '--border-radius': '20px',
                            '--text-color': '#666',
                            '--background-color': '#f5f5f5',
                            '--border-color': '#ddd',
                            padding: '8px 24px'
                        }}
                        onClick={() => navigate('/layout/shouye')}
                    >
                        去逛逛
                    </Button>
                </div>
            ) : (
                <div style={{ backgroundColor: '#fff', marginBottom: '8px' }}>
                    {list.map(item => (
                        <div key={item.title} style={{
                            padding: '16px',
                            borderBottom: '1px solid #f0f0f0',
                            position: 'relative'
                        }}>
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
                                {/* 复选框 */}
                                <div style={{ marginTop: '4px' }}>
                                    <Checkbox
                                        checked={selectedItems.includes(item.title)}
                                        onChange={() => handleItemSelect(item.title)}
                                        style={{
                                            '--icon-size': '20px',
                                            '--font-size': '14px'
                                        }}
                                    />
                                </div>

                                {/* 商品图片 */}
                                <Image
                                    src={item.img}
                                    fit='cover'
                                    width={80}
                                    height={80}
                                    style={{
                                        borderRadius: '8px',
                                        flexShrink: 0
                                    }}
                                />

                                {/* 商品信息 */}
                                <div>
                                    <div style={{ flex: 1, minWidth: 0 }}>
                                        <div>
                                            <div style={{
                                                fontSize: '16px',
                                                fontWeight: '500',
                                                marginBottom: '6px',
                                                lineHeight: '1.4',
                                                color: '#333'
                                            }}>
                                                {item.title}
                                            </div>
                                            <div style={{
                                                fontSize: '13px',
                                                color: '#666',
                                                marginBottom: '8px',
                                                lineHeight: '1.3'
                                            }}>
                                                {item.context}
                                            </div>
                                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                                <div>
                                                    <div style={{
                                                        fontSize: '16px',
                                                        color: '#ff4d4f',
                                                        fontWeight: 'bold',
                                                        marginBottom: '8px',
                                                        width: '100px'
                                                    }}>
                                                        ¥{item.price}
                                                    </div>
                                                </div>
                                                {/* 数量选择器 */}
                                                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                                    <Stepper
                                                        value={quantities[item.title] || 1}
                                                        onChange={(value) => handleQuantityChange(item.title, value)}
                                                        min={1}
                                                        max={99}
                                                        style={{
                                                            '--button-width': '28px',
                                                            '--button-height': '28px',
                                                            '--input-width': '40px',
                                                            '--input-height': '28px'
                                                        }}
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                        {/* 处方药提示 */}

                                    </div>
                                    <div>



                                    </div>

                                </div>


                                {/* 删除按钮 */}
                                <div style={{
                                    position: 'absolute',
                                    top: '16px',
                                    right: '16px',
                                    color: '#999',
                                    fontSize: '18px',
                                    cursor: 'pointer'
                                }} onClick={() => showDeleteModal(item)}>
                                    ×
                                </div>
                            </div>
                            <div style={{
                                marginLeft: 25,
                                marginTop: 10,
                                fontSize: '12px',
                                color: '#ff4d4f',
                                marginBottom: '12px',
                                lineHeight: '1.3'
                            }}>
                                注: 本品属于芳基丙酸类非留体抗炎药，具有解热镇痛及抗炎作用
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* 推荐商品分隔线 */}
            <div style={{
                padding: '16px',
                textAlign: 'center',
                backgroundColor: '#fff',
                marginBottom: '8px'
            }}>
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px'
                }}>
                    <div style={{
                        flex: 1,
                        height: '1px',
                        backgroundColor: '#e0e0e0'
                    }}></div>
                    <span style={{
                        fontSize: '14px',
                        color: '#666',
                        padding: '0 12px'
                    }}>{list.length === 0 ? '————更多推荐————' : '— 您可能需要 —'}</span>
                    <div style={{
                        flex: 1,
                        height: '1px',
                        backgroundColor: '#e0e0e0'
                    }}></div>
                </div>
            </div>

            {/* 推荐商品网格 */}
            <div style={{
                backgroundColor: '#fff',
                padding: '0 16px 16px 16px',
                marginBottom: '20px'
            }}>
                <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(2, 1fr)',
                    gap: '12px'
                }}>
                    {list1.map((item, index) => (
                        <div key={index} style={{
                            backgroundColor: '#fff',
                            borderRadius: '8px',
                            overflow: 'hidden',
                            border: '1px solid #f0f0f0'
                        }}>
                            <div style={{ position: 'relative' }}>
                                {/* 热销标签 */}
                                <div style={{
                                    position: 'absolute',
                                    top: '8px',
                                    left: '8px',
                                    backgroundColor: '#ff9500',
                                    color: '#fff',
                                    fontSize: '10px',
                                    padding: '2px 6px',
                                    borderRadius: '4px',
                                    fontWeight: 'bold',
                                    zIndex: 1
                                }}>
                                    热销
                                </div>

                                {/* 商品图片 */}
                                <Image
                                    src={item.img}
                                    fit='cover'
                                    width='100%'
                                    height={120}
                                    style={{ borderRadius: '8px 8px 0 0' }}
                                />
                            </div>

                            {/* 商品信息 */}
                            <div style={{ padding: '8px' }}>
                                <div style={{
                                    fontSize: '12px',
                                    fontWeight: '500',
                                    marginBottom: '6px',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap',
                                    lineHeight: '1.3',
                                    color: '#333'
                                }}>
                                    {item.name}
                                </div>
                                <div style={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'center'
                                }}>
                                    <span style={{
                                        fontSize: '14px',
                                        color: '#ff4d4f',
                                        fontWeight: 'bold'
                                    }}>
                                        ¥{item.price}
                                    </span>
                                    <div style={{
                                        width: '24px',
                                        height: '24px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        color: '#ccc',
                                        fontSize: '16px'
                                    }}>
                                        🛒
                                    </div>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>

            {/* 额外的底部空间 - 只在有商品时显示 */}
            {list.length > 0 && (
                <div style={{
                    height: '100px',
                    backgroundColor: 'transparent'
                }}></div>
            )}

            {/* 底部结算栏 - 只在有商品时显示 */}
            {list.length > 0 && (
                <div
                    className="fixed-checkout-bar"
                    style={{
                        position: 'fixed',
                        bottom: 0,
                        left: 0,
                        right: 0,
                        background: '#fff',
                        borderTop: '1px solid #e0e0e0',
                        padding: '16px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        boxShadow: '0 -2px 8px rgba(0,0,0,0.1)',
                        height: '70px',
                        zIndex: 999999,
                        transform: 'translateZ(0)',
                        willChange: 'transform',
                        backfaceVisibility: 'hidden',
                        WebkitBackfaceVisibility: 'hidden'
                    }}
                >
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <Checkbox
                            checked={isAllSelected}
                            onChange={handleSelectAll}
                            style={{
                                '--icon-size': '18px',
                                '--font-size': '14px'
                            }}
                        />
                        <span style={{ fontSize: '14px', color: '#333' }}>全选</span>
                    </div>

                    <div style={{
                        fontSize: '18px',
                        color: '#ff4d4f',
                        fontWeight: 'bold',
                        textAlign: 'center',
                        flex: 1,
                        margin: '0 16px'
                    }}>
                        合计: ¥{calculateTotal().toFixed(2)}
                    </div>

                    <Button
                        color='success'
                        size='small'
                        disabled={selectedItems.length === 0}
                        style={{
                            '--border-radius': '24px',
                            '--text-color': '#fff',
                            '--background-color': selectedItems.length === 0 ? '#ccc' : '#07c160',
                            '--border-color': selectedItems.length === 0 ? '#ccc' : '#07c160',
                            minWidth: '80px',
                            height: '36px',
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }}
                        onClick={handleCheckout} >
                        结算({selectedItems.length})
                    </Button>
            </div>
            )}

            {/* 删除确认模态框 */}                                                                                                                                                                                                                                                                                                                                                                      
            <Modal
                visible={deleteModalVisible}
                onClose={cancelDelete}
                title="确认删除"
                content={`确定要删除商品 "${itemToDelete?.title}" 吗？`}
                closeOnMaskClick={false}
                closeOnAction={true}
                actions={[
                    {
                        key: 'confirm',
                        text: '确认',
                        bold: true,
                        danger: true,
                        onClick: handleDelete
                    },
                    {
                        key: 'cancel',
                        text: '取消',
                        onClick: cancelDelete
                    }
                ]}
            />
        </div>
    )
}

export default Gou
